import { HYEventStore } from 'hy-event-store'
import { getPlayDetail, getLyricInfo } from '../service/play_api'
import parseLyric from '../utils/parse-lyric'

const audioContext = wx.getBackgroundAudioManager()

const playerStore = new HYEventStore({
  state: {
    id: 0,
    playDetail: {},
    duration: 0,
    lyricList: [],

    currentTime: 1,
    lyricText: '',
    currentIndex: 0,

    playModeIndex: 0, // 0: 循环播放 1：单曲循环 2：随机播放
    isPlaying: true,
    currentSong: null,

    playMusicIndex: 0,
    playMusicList: [],
    hasPlayMusicIndexList: []
  },
  actions: {
    // 获取播放页数据
    getPlayerDataAction: async function(ctx, { id, isRefresh = false }) {
      // 防止点击同一首歌重新播放
      if (ctx.id == id && !isRefresh) {
        this.dispatch('changePlayingStatuAction', true)
        return
      }

      ctx.id = id
      // 重置歌曲信息
      ctx.playDetail = {}
      ctx.duration = 0
      ctx.lyricList = []
      ctx.currentSong = {}
      ctx.currentIndex = 0
      ctx.currentTime = 1
      ctx.lyricText = ''
      ctx.isPlaying = true
      // 发送请求
      const res = await getPlayDetail(id)
      const { lrc } = await getLyricInfo(id)
      const lyricList = parseLyric(lrc.lyric)
      ctx.playDetail = res.songs[0]
      ctx.duration = res.songs[0].dt
      ctx.lyricList = lyricList

       // 播放对应id的歌曲
      audioContext.stop()
      audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
      audioContext.title = ctx.playDetail.name
      audioContext.autoplay = true

      // 启用监听
      this.dispatch('setupPlayerListenerAction')
    },
    // 监听时间和歌词的变化
    setupPlayerListenerAction: function(ctx) {
      audioContext.onCanplay(() => {
        audioContext.play()
      })
      audioContext.onTimeUpdate(() => {
        ctx.currentTime = audioContext.currentTime * 1000
        // 根据当前时间更新歌词
        if (!ctx.lyricList.length || ctx.lyricList.length === 2) return
        const list = [...ctx.lyricList]
        let i = 0
        for (; i < list.length; i++) {
          if (ctx.currentTime < list[i].time) {
            const currentIndex = i -1
            if (ctx.currentIndex !== currentIndex) {
              if (!list[currentIndex].text) return
              const lyricText = list[currentIndex].text
              ctx.lyricText = lyricText
              ctx.currentIndex = currentIndex
            }
            break
          }
        }
      })
      audioContext.onEnded(() => {
        this.dispatch('changeMusicAction', {})
      })
      audioContext.onPlay(() => {
        ctx.isPlaying = true
      })
      audioContext.onPause(() => {
        ctx.isPlaying = false
      })
    },
    // 监听播放状态的改变
    changePlayingStatuAction: function(ctx, isPlaying) {
      ctx.isPlaying = isPlaying
      ctx.isPlaying ? audioContext.play() : audioContext.pause()
    },
    // 切换播放歌曲
    changeMusicAction: function(ctx, { isNext = true, isEnded = true }) {
      let index = ctx.playMusicIndex
      let id
      if (ctx.playMusicList.length === 1) {
        id = ctx.playMusicList[index].id
        this.dispatch('getPlayerDataAction', { id, isRefresh : true })
        return
      }
     
      switch(ctx.playModeIndex) {
        case 0 :
          index = isNext ? index + 1 : index -1
          if (index == -1) index = ctx.playMusicList.length - 1
          if (index > ctx.playMusicList.length - 1) index = 0
          break
        case 1 :
          if (!isEnded) {
            index = isNext ? index + 1 : index -1
            if (index == -1) index = ctx.playMusicList.length - 1
            if (index > ctx.playMusicList.length - 1) index = 0
          }
          break
        case 2 :
          if (!isNext) {
            const length = ctx.hasPlayMusicIndexList.length
            index = ctx.hasPlayMusicIndexList.at(-2)
            ctx.hasPlayMusicIndexList.splice(length - 1, 1)
            break
          }
          index = Math.floor(Math.random() * (ctx.playMusicList.length - 1))
          ctx.hasPlayMusicIndexList.push(index)
          break
      }
      ctx.playMusicIndex = index

      id = ctx.playMusicList[index].id
      this.dispatch('getPlayerDataAction', { id, isRefresh : true })
    }
  }
})

export {
  audioContext,
  playerStore
}